package com.reportingapplication.teacher;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.reportingapplication.teacher.tools.JSONParser;
import com.reportingapplication.teacher.tools.ID;

import android.os.AsyncTask;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

/**
 * Activity which asks teacher to write his name
 * @author Keith Davelaar
 */
public class SignupActivity extends Activity {

	/** Google variable **/
	private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
	/** Progress bar **/
	private ProgressDialog pDialog;    
	
	/**
	 * Called when the Activity is created.
	 * Standard.
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		this.setTitle(ID.TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_signup);
	}

	/**
	 * Standard.
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	/**
     * Check the device to make sure it has the Google Play Services APK. If
     * it doesn't, display a dialog that allows users to download the APK from
     * the Google Play Store or enable it in the device's system settings.
     */
    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Log.i(ID.ERROR+ID.SIGNUP, "This device is not supported.");
                finish();
            }
            return false;
        }
        return true;
    }

	/** Called when the user clicks the OK button */
	public void nextMenu(View view) {
		// Get the name from the textfield.
		EditText nameField = (EditText) findViewById(R.id.nameField);
		// Something has to be filled in, otherwise do nothing.
		if(nameField.getText() != null){
			(new SaveTeacher()).execute(nameField.getText().toString());
		}
	}
	
	/**
     * Class which saves the name of a new teacher
     */
    private class SaveTeacher extends AsyncTask<String, String, String> {
    	
    	private static final String SENDER_ID = "753935966802";
        private String google_id;
        private boolean registered;
        
    	/**
         * Before starting background thread Show Progress Dialog
         */
    	@Override
		protected void onPreExecute() {
    		super.onPreExecute();
    		registered = false;
            pDialog = new ProgressDialog(SignupActivity.this);
            pDialog.setMessage("Bezig te registreren. Een moment geduld...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
		}

		@SuppressLint("NewApi")
		@Override
		protected String doInBackground(String... args) {
			// Check device for Play Services APK.
			if (checkPlayServices()) {
				// Check if there is not already a registration
				google_id = getSharedPreferences(ID.PREFS_NAME, 0).getString(ID.GOOGLE_ID, ID.EMPTY);
				if (google_id.equals(ID.EMPTY)) {
					// Checks succeeded, get GCM for registration.
					GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(SignupActivity.this);
					try {
						boolean successful = false;
						while(!successful){
							// Try to register.
							google_id = gcm.register(SENDER_ID);
							// Get the name of the teacher and save this, together
							// with the newly generated google_id
							List<NameValuePair> params = new ArrayList<NameValuePair>();
							String name = args[0];
							params.add(new BasicNameValuePair(ID.TEACHER_NAME, name));
							params.add(new BasicNameValuePair(ID.GOOGLE_ID, google_id));
							// Getting JSON string from URL
							JSONParser jParser = new JSONParser();
							JSONObject json = jParser.makeHttpRequest(ID.URL_ADD_TEACHER, ID.POST_REQUEST, params);
							// Check that the request was successful
							int success = json.getInt(ID.TAG_SUCCESS);
							if (success == 1) {
								// If successful log in teacher and save his/her google_id
								Editor edit = getSharedPreferences(ID.PREFS_NAME, 0).edit();
								edit.putBoolean(ID.LOGGED_IN, true);
								edit.putString(ID.GOOGLE_ID, google_id);
								edit.putString(ID.NAME, name);
								edit.commit();
								// closing this screen
								successful = true;
								registered = true;
								finish();
							}
						}
					} catch (IOException e) {
						Log.e(ID.ERROR, "Error: " + e.getMessage());
					} catch (JSONException e) {
						Log.e(ID.ERROR, e.toString());
					} catch (Exception e) {
						Log.e(ID.ERROR, "Error: "+e.getClass().getName());
					}
				}else{
					registered = true;
				}
			} else {
				Log.e(ID.ERROR, "No valid Google Play Services APK found.");
			}
			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 **/
		@Override
		protected void onPostExecute(String file_url) {
			// Dismiss the dialog once done
			pDialog.dismiss();
			if(!registered){
				Context context = getApplicationContext();
				CharSequence text = "Registreren niet gelukt door verbindingsprobleem, probeer a.u.b. later opnieuw";
				int duration = Toast.LENGTH_LONG;
				Toast toast = Toast.makeText(context, text, duration);
				toast.show();
			}else{
				// Return to the previous activity
				SignupActivity.this.finish();
			}
		}
	}
}
